<template id='profile'>
  <div class="profile">
    <div class="pc disCenter">
      <transition :name="profileData.cardTransition">
        <div class="content" @click.stop v-show="profileData.isShow">
          <div class="leftPath">
            <div class="headImg">
              <img :src="userInfo.icon" alt="" />
              <input type="file" title="" @change="changeHeader($event)" accept="image/png,image/gif,image/jpeg" />
            </div>
            <div class="userName disCenter">
              <input spellcheck="false" autocomplete="off" v-model="userInfo.nickname"
                :disabled="profileData.isReadonly" ref="nickname" maxlength="16" @blur="saveUserName('blur')"
                :class="{ isReadonly: !profileData.isReadonly }" @keyup.enter="saveUserName('enter')" />
              <img :src="profileData.editBtn" alt="Change" @click="changeUserName" />
            </div>
            <p class="time">Account since: {{userInfo.createtime}}</p>
            <p class="total">Total:{{userInfo.total_entries}}</p>
            <p>Ideas: <span>{{userInfo.ideas}}</span></p>
            <p>Book highlights: <span>{{userInfo.book_highlights}}</span></p>
            <p>Web clippings: <span>{{userInfo.web_clippings}}</span></p>
            <p class="last">Last seen: {{userInfo.last_login_time}}</p>
          </div>
          <div class="line"></div>
          <div class="rightPath">
            <p>Email address:</p>
            <div class="email sCenter">
              <p>{{ userInfo.email }}</p>
              <p class="change alink" @click="changeEmail">Change</p>
            </div>
            <p class="desc">
              Here is the email address used for signing into your account.
            </p>
            <p class="password">
              <span class="alink" @click="changePassword">Change account password</span>
            </p>
            <p class="signOut">
              <span class="alink" v-if="profileData.signOutStep == 1" @click="profileData.signOutStep = 2">Sign
                out</span>
              <span class="alink" v-else @click="signOut">Click again to sign out</span>
            </p>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
import { setCookie, getCookie } from "@/utils/cookie.js";
import { createNamespacedHelpers } from "vuex";
const profile = createNamespacedHelpers("profile");
const common = createNamespacedHelpers("common");
const home = createNamespacedHelpers("home");
import { showMessage } from "@/utils";
export default {
  name: "",
  components: {},
  props: {},
  // 定义属性
  data() {
    return {
      ws: "",
      timeout: 1800000,
      serverTimeoutObj: null,
    };
  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
    ...profile.mapState(["profileData"]),
    ...common.mapState(["userInfo"]),
  },
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    ...common.mapMutations(["userSignout"]),
    ...common.mapActions(["getUserInfo", "updateUserInfo"]),
    ...home.mapActions(['getEntries']),
    //修改密码
    changePassword() {
      this.$parent.closeProfile();
      setTimeout(() => {
        this.$parent.openPassword();
      }, 300);
    },
    //修改邮箱
    changeEmail() {
      this.$parent.closeProfile();
      setTimeout(() => {
        this.$parent.openEmail();
      }, 300);
    },
    //修改昵称
    changeUserName() {
      this.profileData.isReadonly = false;
      this.$nextTick(() => {
        let length = this.userInfo.nickname.length;
        let input = this.$refs.nickname;
        input.focus();
        input.selectionStart = length;
        input.selectionEnd = length;
      });
    },
    //保存昵称
    saveUserName(type) {
      if (type == "enter") {
        this.$refs.nickname.blur();
      } else {
        this.updateUserInfo();
        this.profileData.isReadonly = true;
      }
    },
    //修改头像
    changeHeader(e) {
      let avatar = e.target.files[0];
      if (!avatar) return;
      let imgSize = avatar.size;
      if (imgSize > 1024 * 1024 * 2) {
        showMessage("picture must be less than 2Mb", "warning");
        return;
      }
      if (
        avatar.type != "image/png" &&
        avatar.type != "image/jpeg" &&
        avatar.type != "image/gif"
      ) {
        showMessage("upload format is incorrect", "warning");
        return;
      }

      const reader = new FileReader(); //实例化一个reader文件
      reader.readAsDataURL(avatar); //readAsDataURL方法将图片转为base64格式存储于result中
      reader.onload = (e) => {
        this.uploadAvatar(avatar);
      };
      // 上传失败
      reader.onerror = (res) => {
        showMessage(res, "error");
      };
      e.target.value = "";
    },

    async uploadAvatar(file) {
      let formData = new FormData();
      formData.append("userId", this.userInfo.userId);
      formData.append("file", file);
      let res = await this.$api.profile.updateUserIconApi(formData);
      if (this.$isCode(res)) {
        showMessage("upload succeeded", "success");
        this.getUserInfo();
      }
    },
    signOut() {
      this.profileData.signOutStep = 1;
      this.$parent.closeProfileAll();
      setTimeout(() => {
        this.userSignout();
        console.log(getCookie('sessionID'));
        this.ws.send(JSON.stringify({ 'loginOut': getCookie('sessionID') }));
      }, 300);
    },
    resetSocket() {
      clearTimeout(this.serverTimeoutObj);
      this.startSocket()
    },
    startSocket() {
      let that = this
      this.serverTimeoutObj = setInterval(function () {
        if (that.ws.readyState == 1) {
          console.log("连接状态，发送消息保持连接");
          that.ws.send("ping");
          // 如果获取到消息，说明连接正常，重置心跳检测
          that.resetSocket()
        } else {
          console.log("断开连接，尝试重连");
          that.connectSocket();
        }
      }, this.timeout)
    },
    connectSocket() {
      let that = this
      if ("WebSocket" in window) {
        that.ws = new WebSocket("wss://enchi.io/metamemory/ws/myWebSocket")
        // 打开一个 web ws
        that.ws.onopen = function () {
          that.resetSocket()
          // ws.send("发送数据")
        }
        that.ws.onmessage = function (evt) {
          let received_msg = JSON.parse(evt.data)
          console.log("数据已接收...", received_msg.status)
          if (received_msg.status == 1) {
            setCookie("pageSessionID", received_msg.sessionId, 7);
          } else if (received_msg.status == 3) {
            that.getEntries()
          } else if (received_msg.status == 4) {
            that.userSignout()
          }
        }

        that.ws.onclose = function () {
          // 关闭 websocket
          console.log("连接已关闭...")
        }
      } else {
        // 浏览器不支持 WebSocket
        console.log("您的浏览器不支持 WebSocket!")
      }
    },
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() { },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.connectSocket();
  },
  beforeCreate() { }, // 生命周期 - 创建之前
  beforeMount() { }, // 生命周期 - 挂载之前
  beforeUpdate() { }, // 生命周期 - 更新之前
  updated() { }, // 生命周期 - 更新之后
  beforeDestroy() { }, // 生命周期 - 销毁之前
  destroyed() { }, // 生命周期 - 销毁完成
  activated() { }, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang='less' scoped>
.profile {
  .pc {
    .content {
      width: 797px;
      height: 528px;
      background-color: #ffffff;
      box-shadow: 0 11px 15px -7px rgba(0, 0, 0, 0.2),
        0 24px 38px 3px rgba(0, 0, 0, 0.14), 0 9px 46px 8px rgba(0, 0, 0, 0.12);
      border-radius: 12px;
      border: solid 1px #888888;
      padding: 50px;
      position: absolute;
      z-index: 100;
      backface-visibility: hidden;
      -webkit-backface-visibility: hidden;
      display: flex;

      .leftPath {
        display: flex;
        flex-direction: column;

        p {
          margin-top: 5px;
          font-size: 12px;
          color: @tColor;
        }

        .headImg {
          width: 80px;
          height: 80px;
          border-radius: 50%;
          margin: 0 auto;
          position: relative;

          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }

          input {
            margin: 0;
            width: 80px;
            height: 80px;
            border-radius: 50%;
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
            overflow: hidden;
            cursor: pointer;
            opacity: 0;
          }
        }

        .userName {
          margin-top: 15px;

          input {
            width: 147px;
            font-size: 18px;
            color: @dColor;
            border: none;
            background-color: #ffffff;
          }

          input:focus {
            border: none;
            outline: 0;
            -webkit-box-shadow: none;
            box-shadow: none;
          }

          .isReadonly {
            color: @tColor;
          }

          img {
            width: 16px;
            height: 16px;
            box-shadow: none;
            cursor: pointer;
            margin-left: 6px;
          }
        }

        .time {
          font-size: 12px;
          color: @tColor;
          margin-top: 10px;
        }

        .total {
          margin-top: 32px;
        }

        .last {
          margin-top: 28px;
        }
      }

      .line {
        width: 2px;
        background: rgba(168, 168, 168, 0.3);
        margin: 0 33px 0 42px;
      }

      .rightPath {
        width: 100%;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        p {
          font-size: 12px;
          color: @tColor;
          margin-top: 20px;
        }

        .email {
          p {
            font-size: 18px;
            color: @dColor;
          }

          .change {
            font-size: 12px;
            color: @tColor;
            cursor: pointer;
            border-bottom: 1px solid @tColor;
          }
        }

        .desc {
          font-size: 14px;
          color: @dColor;
          margin-top: 10px;
        }

        .password {
          margin-top: 20px;

          span {
            font-size: 12px;
            font-family: Helvetica;
            cursor: pointer;
            border-bottom: 1px solid @tColor;
          }
        }

        .signOut {
          margin-top: auto;

          span {
            font-size: 12px;
            font-family: Helvetica;
            cursor: pointer;
            border-bottom: 1px solid @tColor;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 980px) {
  .profile {
    .pc {
      .content {
        width: 600px;
        padding: 25px;

        .line {
          margin: 0 23px 0 32px;
        }
      }
    }
  }
}

@media screen and (max-width: 650px) {
  .profile {
    .pc {
      .content {
        padding-top: 17px;
        width: 304px;
        height: 451px;
        flex-direction: column;

        .leftPath {
          width: fit-content;
          margin: 0 auto;

          .userName {
            img {
              width: 20px;
              height: 20px;
            }
          }

          .time {
            font-size: 14px;
          }

          .total {
            margin-top: 10px;
            font-size: 14px;
          }

          p {
            font-size: 14px;
            margin-top: 3px;
          }

          .last {
            font-size: 14px;
            margin-top: 12px;
          }

          .line {
            display: none;
          }
        }

        .rightPath {
          margin-top: 12px;
          padding-top: 13px;
          border-top: solid 1px rgba(168, 168, 168, 0.3);

          p {
            font-size: 14px;
            margin-top: 0;
          }

          .email {
            margin-top: 10px;

            .change {
              font-size: 14px;
              margin-top: -54px;
            }
          }

          .desc {
            margin-top: 5px;
          }

          .password {
            span {
              font-size: 14px;
            }
          }

          .signOut {
            margin-top: 60px;

            span {
              font-size: 14px;
            }
          }
        }
      }
    }
  }
}
</style>